<template>
	<custom-nav :showBackArrow="true" :title="'蓝牙'"></custom-nav>
	<view class="page-setting" :style="pagePaddingTop" >
		<view class="wrap-logout" @tap="toBlueTooth">
			<view style="font-weight: bold;">蓝牙</view>
			<u-switch v-model="showBluetooth" size="60" active-color="#00E979" @change="switchChange" ></u-switch>
		</view>
		<view class="find_text" >蓝牙设置打开时，可被发现为“{{ deviceInfo }}”</view>
		<view class="device_title" v-if="list.length > 0" >我的设备</view>
		<view class="device_list" v-if="list.length > 0" >
			<!-- <view class="device_item device_active" >
				<view class="device_left" >
					<view>Buick IntelliLink（文字溢出效果...</view>
					<view>FC:08:F0:A9:B6:59</view>
				</view>
				<view class="device_right" >
					已连接
					<image src="/static/bluetooth/right_active.png" mode="aspectFill" class="device_right_icon" />
				</view>
			</view> -->
			
			<view class="device_item" v-for="(item, index) in list" :key="index" :class="{ 'device_active': item.connect }" @click="toConnect(item, index)"  >
				<view class="device_left" >
					<view>{{ item.mid_table_remark_001 }}</view>
					<view>{{ item.mid_table_remark_002 }}</view>
				</view>
				<view class="device_right" @click.stop="listToDevice(item)">
					<view v-if="!item.is_connect_loading" >
						{{ item.connect ? '已连接' : '未连接' }}
					</view>
					
					<image src="/static/bluetooth/loading.png" mode="aspectFill" class="connect_loading" v-if="item.is_connect_loading" />
					
					<image src="/static/bluetooth/right_active.png" mode="aspectFill" class="device_right_icon" v-if="item.connect" />
					<image src="/static/bluetooth/right.png" mode="aspectFill" class="device_right_icon" v-else />
				</view>
			</view>
		</view>
		
		<view class="device_title" >
			<view>其他设备</view>
			<image src="/static/bluetooth/refresh.png" mode="aspectFill" class="refresh_icon" @click="handleRefresh" />
		</view>
		<view class="other_list" >
			<view class="other_item" v-for="(item, index) in deviceList" :key="index" @click="toDevice(item)" >
				<image src="/static/bluetooth/bluetooth.png" mode="aspectFill" class="bluetooth_icon" />
				<view class="other_right" >
					<view class="other_title" >{{ item.name }}</view>
				</view>
			</view>
			
			<!-- <view class="other_item" >
				<image src="/static/bluetooth/bluetooth.png" mode="aspectFill" class="bluetooth_icon" />
				<view class="other_right" >
					<view class="other_title" >MI AIRDOTS BASIC_L</view>
					<view class="ohter_status" >连接中......</view>
				</view>
			</view> -->
		</view>
	</view>
</template>

<script setup>
import {
	ref,
	computed,
	onMounted,
} from "vue"
import Base64 from "@/libs/js-base64/index.js"
const showBluetooth = ref(false)
import CustomNav from "@/components/custom-nav/index.vue"
import {
		getNavHeightTop
} from "@/stores/navStore.js"
import {
	getConnectDevices
} from '@/http/apis/bluetoothAPI.js'
import {
		onShow,
		onUnload,
		onReachBottom
} from "@dcloudio/uni-app"
import {
	useUser
} from "@/hooks/useUser.js"
// 用户信息
let userInfo = ref(null)
const userStore = useUser();


let navHeightInfo = getNavHeightTop();
const pagePaddingTop = ref({
	"paddingTop": (navHeightInfo.navTotalHeight + uni.upx2px(24)) + 'px'
})
const deviceList = ref([])
const list = ref([])
const deviceInfo = ref('')
const handleRefresh = () => {
	if(!showBluetooth.value) {
		uni.showToast({
			title: '请打开蓝牙搜索',
			icon: 'none',
			duration: 2000
		})
		return false
	}
	deviceList.value = []
	startBluetoothDevicesDiscovery()
}

const toConnect = (item, index) => {
	const { connect } = item;
	!connect ? createBLEConnection(item, index) : disconnectBluetooth(item.mid_table_remark_002, index);	
}

const disconnectBluetooth = (deviceId, index) => {
	uni.showModal({
		title: '提示',
		content: '是否断开连接？',
		success(res) {
			if(res.confirm) {
				uni.closeBLEConnection({
					deviceId,
					success(res) {
						uni.showToast({
							title: '蓝牙已断开',
							icon: 'none',
							duration: 2000
						})
						getConnectedBluetoothDevices()
						setConnect('connect', false, index)
					},
					fail(res) {
						uni.showToast({
							title: '操作失败',
							icon: 'none',
							duration: 2000
						})
					}
				})
			}
		}
	})
}

const setConnect = (type, connect, index) => {
	const newData = [...list.value]
	newData[index][type] = connect
	list.value = [...newData]
}


const createBLEConnection = (item, index) => {
	const { mid_table_remark_001, mid_table_remark_002 } = item
	const { id_public_user_info } = userInfo.value
	setConnect('is_connect_loading', true, index)
	uni.createBLEConnection({
		deviceId: mid_table_remark_002,
		async success(res) {
			console.log('进来了...')
			await setConnect('is_connect_loading', false, index)
			getConnectedBluetoothDevices()
			// // 判断之前是否连接过 ...
			// if(!isConnectFlag()) {
			// 	const result = await insertBluetooth({
			// 		id_public_user_info,
			// 		invoke_method: 'public_insert_or_update_middle_table',
			// 		pre_db_para_middle_table_name: 'public_middle_table_lite_mod_bluetooth',
			// 		type_middle_app: '23001',
			// 		type_inner_app: '10001',
			// 		is_online: '0',
			// 		pre_db_para_begin_idx: '0',
			// 		pre_db_para_length_4_list: '10',
			// 		mid_table_remark_001,
			// 		mid_table_remark_002: Base64.encode(mid_table_remark_002),
			// 		mid_table_remark_003: '',
			// 		mid_table_remark_004: '401',
			// 		mid_table_remark_040: new Date().getTime()
			// 	})
			// }
		},
		fail(res) {
			console.log('失败：', res)
			setConnect('is_connect_loading', false, index)
			uni.showToast({
				title: '连接失败',
				icon: 'none',
				duration: 2000
			})
		}
	})
}

const listToDevice = (obj) => {
	let item = {
		deviceId: obj.mid_table_remark_002,
		localName: obj.mid_table_remark_001,
		name: obj.mid_table_remark_001,
	}
	
	if(!showBluetooth.value) {
		uni.showToast({
			title: '请打开蓝牙搜索',
			icon: 'none',
			duration: 2000
		})
		return false
	}
	
	uni.navigateTo({
		url: '/pages/setting/deviceSetting?deviceInfo=' + JSON.stringify(item)
	})
}

const toDevice = (item) => {
	if(!showBluetooth.value) {
		uni.showToast({
			title: '请打开蓝牙搜索',
			icon: 'none',
			duration: 2000
		})
		return false
	}
	
	uni.navigateTo({
		url: '/pages/setting/deviceSetting?deviceInfo=' + JSON.stringify(item)
	})
}

/**
 * 获取设备
 * */
const getBluetoothDevices = () => {
	let tempDevices = {}; // 临时对象用于存储已发现的设备
	uni.getBluetoothDevices({
		success: function(res) {
			//将BluetoothList遍历给用户，当用户点击连接某个蓝牙时调用4.0
			let devices = res.devices
			let uniqueDevices = devices.filter(function(device) {
		          if (!tempDevices[device.deviceId]) {
		            tempDevices[device.deviceId] = true;
		            return true;
		          }
		          return false;
		        });
			deviceList.value = uniqueDevices.filter(item => { return item.name || item.localName })
		},
		fail: function() {
			console.log("搜索蓝牙设备失败")
		}
	})
}

/**
 * 发现外围设备
 * */
const onBluetoothDeviceFound = () => {
	uni.onBluetoothDeviceFound(devices => {
		// console.log('开始监听寻找到新设备的事件');
		getBluetoothDevices();
	});
}

/**
 * 开始搜索蓝牙设备
 * */
const startBluetoothDevicesDiscovery = () => {
	uni.startBluetoothDevicesDiscovery({
		success: e => {
			onBluetoothDeviceFound();
		},
		fail: e => {
			console.log('搜索蓝牙设备失败，错误码：' + e.errCode);
			if (e.errCode !== 0) {
				initTypes(e.errCode);
			}
		}
	});
}

const switchChange = (event) => {
	if(event) {
		console.log('打开蓝牙了 ...')
		openBluetoothAdapter()
		getConnectedBluetoothDevices()
	}else {
		console.log('关闭蓝牙了...')
		stopBluetoothDevicesDiscovery()
	}
}

const initTypes = (code, errMsg) => {
		switch (code) {
			case 10000:
				toast('未初始化蓝牙适配器');
				break;
			case 10001:
				toast('未检测到蓝牙，请打开蓝牙重试！');
				break;
			case 10002:
				toast('没有找到指定设备');
				break;
			case 10003:
				toast('连接失败');
				break;
			case 10004:
				toast('没有找到指定服务');
				break;
			case 10005:
				toast('没有找到指定特征值');
				break;
			case 10006:
				toast('当前连接已断开');
				break;
			case 10007:
				toast('当前特征值不支持此操作');
				break;
			case 10008:
				toast('其余所有系统上报的异常');
				break;
			case 10009:
				toast('Android 系统特有，系统版本低于 4.3 不支持 BLE');
				break;
			default:
				toast(errMsg);
		}
	}

/**
 * 初始化蓝牙设备
 * */
const openBluetoothAdapter = () => {
	uni.openBluetoothAdapter({
		success(e) {
			console.log('初始化蓝牙成功:', JSON.stringify(e))
			startBluetoothDevicesDiscovery()
		},
		fail(e) {
			console.log('初始化蓝牙失败:', e)
			uni.showModal({
				title: '提示',
				content: '蓝牙初始化失败，请在系统设置中打开蓝牙！',
				showCancel: false
			})
		}
	})
}

// 判断之前是否连接过
const isConnectFlag = () => {
	const { deviceId } = params.value
	let index = list.value.findIndex(item => { return item.mid_table_remark_002 == deviceId })
	return index > -1
}

const stopBluetoothDevicesDiscovery = () => {
	uni.stopBluetoothDevicesDiscovery({
		success() {
			console.log('停止搜索外围设备')
		}
	})
}

const getSystemInfo = () => {
	console.log(uni.getSystemInfoSync())
	let deviceModel = uni.getSystemInfoSync().deviceModel
	deviceInfo.value = deviceModel
}

const getList = () => {
	userStore.getUserInfo().then(async res => {
		userInfo.value = res?.public_user_info || {};
		const { id_public_user_info } = userInfo.value
		const result = await getConnectDevices({
			invoke_method: 'public_load_middle_table_list',
			pre_db_para_middle_table_name: 'public_middle_table_lite_mod_bluetooth',
			type_middle_app: '23001',
			type_inner_app: '10001',
			is_online: '0',
			pre_db_para_begin_idx: '0',
			pre_db_para_length_4_list: '10',
			id_public_user_info
		})
		list.value = result.page_content
		list.value.map(item => {
			item.connect = false
			item.is_connect_loading = false
			item.mid_table_remark_002 = Base64.decode(item.mid_table_remark_002)
			item.mid_table_remark_001 = Base64.decode(item.mid_table_remark_001)
		})
		
		console.log('list:', list.value)
		
		if(showBluetooth.value) {
			getConnectedBluetoothDevices()
		}
	}, err => {
		console.log(err, '>>>userinfo')
	})
	
	
}

/**
 * 获取已连接的设备
 * */
const getConnectedBluetoothDevices = () => {
	uni.getConnectedBluetoothDevices({
		success(res) {
			let devices = res.devices
			devices.map(item => {
				list.value.map(child => {
					if(item.deviceId == child.mid_table_remark_002) {
						child.connect = true
					}else {
						child.connect = false
					}
				})
			})
			
			// 我的设备排序
			sortList();
		},
		fail(res) {
			console.log('fail:', res)
		}
	})
}

const sortList = () => {
	const list1 = []
	const list2 = []
	list.value.map(item => {
		item.connect ? list1.push(item) : list2.push(item)
	})
	list.value = list1.concat(list2)
}

onShow(() => {
	getList()
})

onMounted(() => {
	getSystemInfo()
})


</script>

<style scoped lang="less" >
.page-setting {
	position: relative;
	width: 100%;
	min-height: 100vh;
	background-color: #182836;
	font-size: 30rpx;
	// font-family: PingFang SC;
	font-weight: 500;
	color: #FFFFFF;
	line-height: 30rpx;
	box-sizing: border-box;
	padding: 24rpx 32rpx;
	
	image {
		display: block;
	}
	
	.wrap-logout {
		position: relative;
		height: 114rpx;
		padding: 0 32rpx;
		background: #2D4052;
		border-radius: 28rpx;
		box-sizing: border-box;
		display: flex;
		display: -webkit-flex;
		align-items: center;
		justify-content: space-between;
	}
	
	.find_text {
		font-size: 20rpx;
		color: rgba(255, 255, 255, .7);
		margin: 20rpx 0 0 0;
		box-sizing: border-box;
		padding: 0 0 0 32rpx;
	}
	
	.device_title {
		font-size: 32rpx;
		color: #fff;
		padding: 55rpx 32rpx 32rpx 32rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-weight: bold;
		
		.refresh_icon {
			width: 64rpx;
			height: 64rpx;
		}
	}
	
	.device_item {
		height: 156rpx;
		background-color: #2D4052;
		border-radius: 28rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 0 32rpx;
		margin: 0 0 24rpx 0;
		
		.device_left {
			display: flex;
			flex-direction: column;
			justify-content: center;
			width: 458rpx;
			height: 100%;
			box-sizing: border-box;
		}
		
		.device_left > view:first-of-type {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			font-weight: bold;
		}
		
		.device_left > view:last-of-type {
			font-size: 24rpx;
			margin: 22rpx 0 0 0;
			color: rgba(255, 255, 255, .5)
		}
		
		.device_right {
			font-size: 24rpx;
			color: rgba(255, 255, 255, .5);
			display: flex;
			align-items: center;
			
			.connect_loading {
				width: 55rpx;
				height: 55rpx;
				margin: 0 14rpx 0 0;
			}
		}
		
		.device_right_icon {
			width: 44rpx;
			height: 44rpx;
			display: block;
			margin: 0 0 0 16rpx;
		}
		
		
	}
	
	.device_item:last-of-type {
		margin-bottom: 0;
	}
	
	.device_active {
		background-color: #00FFF6;
		
		.device_left > view:first-of-type {
			color: #182836;
		}
		
		.device_left > view:last-of-type {
			color: rgba(24,40,54, .5);
		}
		
		.device_right {
			color: #182836;
		}
	}
	
	.other_list {
		box-sizing: border-box;
		padding: 0 32rpx;
		
		.other_item {
			display: flex;
			align-items: center;
			margin: 0 0 48rpx 0;
		}
		
		.other_item:last-of-type {
			margin-bottom: 0;
		}
		
		.bluetooth_icon {
			width: 64rpx;
			height: 64rpx;
			margin: 0 48rpx 0 0
		}
		
		.other_title {
			font-size: 30rpx;
			color: #fff;
			font-weight: 600;
		}
		
		.ohter_status {
			font-size: 24rpx;
			color: rgba(255, 255, 255, .5);
			margin: 10rpx 0 0 0;
		}
	}
	
}


</style>